//
//  YDBuyStrategyController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/15.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDBuyStrategyController.h"
#import "YDBuyStrategyTitleButton.h"
#import "YDOneRechargeViewController.h"
#import "YDBuyStrategyTopView.h"
#import "YDBuyStrategyCell.h"
#import "YDBuyStrategyTableHeaderView.h"
#import "YDBuyStrategyTableFooterView.h"
#import "YDBuySelectedRateView.h"
#import "YDStrategyTypeModel.h"
#import "YDLossRateModel.h"
#import "YDAccountMonyModel.h"
#import "YDPayAlertView.h"
#import "YDPaymentPasswordController.h"

#import "YDRechargeWithdrawalButtonView.h"//立即买入
#import "YDModifyPayPasswordViewController.h"

#import "YDSelectBuyBlockCell.h" //选择申请资金 杠杆cell
#import "YDAccountMonyModel.h"
#import "YDSelectBuyBlockFooter.h"
#import "YDRechargeController.h"


@interface YDBuyStrategyController ()<UITableViewDelegate , UITableViewDataSource , SYRechargeWithdrawalButtonViewDelegate , SYBuySelectedRateViewDelegate , SYBuyStrategyCellDelegate>
//记录哪一个策略
@property (nonatomic , assign) NSInteger strategy;

//显示单只股票信息的view
@property (nonatomic , weak) YDBuyStrategyTopView *topView;

//tableView
@property (nonatomic , weak) UITableView *tableView;

//申请资金的数组
@property (nonatomic , strong) NSMutableArray *fundsArray1;


@property (nonatomic , weak) YDRechargeWithdrawalButtonView *buttonView;

@property (nonatomic , weak) YDBuySelectedRateView *rateView;
//选择止损，止盈模型数组
//@property (nonatomic , strong) NSMutableArray *selectedRateArray;

//当前的止损率
@property (nonatomic, copy) NSString *currenLosetRate;

@property (nonatomic, strong)NSNumber *currentLossMultiple; //当前的杠杆倍数



//当前的止盈率
//@property (nonatomic, copy) NSString *currenUptRate;

//是否自动支付开关
@property (nonatomic, strong)UISwitch *autoPaySwitch;

@property (nonatomic, strong)NSString *currentApplyMoney;// 当前申请资金
/**
 用于刷新fooerview section == 1的footer
 */
@property (nonatomic, strong)YDBuyStrategyTableFooterView *footer;
/**
 section == 0 的footer
 */
@property (nonatomic, strong)YDSelectBuyBlockFooter *footer0;
//策略数组
@property (nonatomic, strong) NSMutableArray *strategyList;

@property (nonatomic, strong)YDStrategyTypeModel *curretStrategyModel;//当前的策略模型


//当前股票的最新信息
@property (nonatomic, copy)NSDictionary *currentStock;

@property (nonatomic, copy)NSString *allMoneyStr; //所有金额

@property (nonatomic, strong)NSMutableArray *selectBlockList; //申请资金 杠杆倍数 持仓天数 数据源

@property (nonatomic, strong)NSMutableArray *indexList; //储存index数组

@property (nonatomic, strong)NSMutableArray *gangganList; //杠杆倍数


@end

@implementation YDBuyStrategyController

-(NSMutableArray *)fundsArray1
{
    if (_fundsArray1 == nil) {
        _fundsArray1 = [NSMutableArray new];
    }
    return _fundsArray1;
}

-(NSMutableArray *)gangganList
{
    if (_gangganList == nil) {
        _gangganList = [NSMutableArray new];
    }
    return _gangganList;
}
-(NSMutableArray *)indexList
{
    if (_indexList == nil) {
        _indexList = [NSMutableArray new];
    }
    return _indexList;
}
-(NSMutableArray *)selectBlockList
{
    if (_selectBlockList == nil) {
        _selectBlockList = [NSMutableArray new];
    }
    return _selectBlockList;
}

-(NSMutableArray *)strategyList
{
    if (!_strategyList) {
        _strategyList = [NSMutableArray new];
    }
    return _strategyList;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"发布策略";
    self.view.backgroundColor = NumberColor(247, 247, 247);
  
    [self getStockNewMarket];
    
}
//加载单只股票信息
-(void)getStockNewMarket
{
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    NSString *url = [NSString stringWithFormat:@"%@%@",@"/stock/market/" , self.stockCode];
    NSString *baseUrl = [NSString stringWithFormat:@"%@%@",baseUrlHttp , url];
    NSString *authToken = [[SYUserDataManger sharedInstance] getUserToken];
    BaseNetRequest *request = [[BaseNetRequest alloc] initWithRequestMethod:GETMethod];
    [request sessionRequestWithDictionary:nil andURLString:baseUrl andAuthToken:authToken WithSuccessBlock:^(NSDictionary *resultDict) {
        
        DDLog(@"resultDict = %@" , resultDict)
        if ([resultDict[@"code"] integerValue] == 200) {
            self.currentStock = resultDict[@"result"];
            if ([resultDict[@"result"][@"status"] integerValue] == 1) {
                [self loadData];
                
            }else{
                [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"改股票现已停牌，请留意实时信息" isExistNav:YES];
        
            }
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                      isExistNav:YES];
    }];
}
#pragma mark - 请求策略数据
- (void)loadData
{
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetStrategyInfo WithSuccessBlock:^(NSDictionary *resultDict) {
          [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
         if ([resultDict[@"code"] integerValue] == 200)
         {
             self.strategyList = [YDStrategyTypeModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
             [self configurationDataSourceWithIndex:0 isTwice:NO];
             [self addChildViews];
             
         }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage text:@"网络异常"
                                                      isExistNav:YES];
    }];
}


/**
 配置服务器返回的数据
 */
- (void)configurationDataSourceWithIndex:(NSInteger)index isTwice:(BOOL)isTwice
{
    //默认T+1；
    if (self.strategyList.count) {
        
        
        
        [self.selectBlockList removeAllObjects];
//        [self.fundsArray1 removeAllObjects];
//        [self.gangganList removeAllObjects];
        
        YDStrategyTypeModel *model = (YDStrategyTypeModel *)[self.strategyList objectAtIndex:index];
        self.curretStrategyModel = model;
        
        NSMutableArray *moneys = [NSMutableArray new];
        for (YDAccountMonyModel *model1 in model.amountValues) {//金额
            [moneys addObject:model1.wanValue];
        }
        
        
        NSMutableArray *tianshu = [NSMutableArray new];
        for ( YDStrategyTypeModel *model in self.strategyList) {//天数
            [tianshu addObject:model.cycle];
        }
        
        NSMutableArray *ganggan = [NSMutableArray new];
        
        for (YDLossRateModel *model1 in model.losses) { //杠杆
            [ganggan addObject:[NSString stringWithFormat:@"%@",model1.multiple]];
            
        }
        
        [self.selectBlockList addObject:moneys];
        [self.selectBlockList addObject:ganggan];
        [self.selectBlockList addObject:tianshu];
        
        if (!isTwice) {
            //第一次默认给下标都是0
            [self.indexList addObjectsFromArray:@[@0,@0,@0]];
           
            //每次默认选择第一个申请金额
            self.curretStrategyModel.currentApplyMoeny = ((YDAccountMonyModel *)[model.amountValues firstObject]).wanValue;
            
           // self.selectedRateArray = model.losses;
            //每次默认选择一个止损率
            self.currenLosetRate = ((YDLossRateModel *)[model.losses firstObject]).point;
            //每次默认选择一个杠杆倍数
            self.currentLossMultiple = ((YDLossRateModel *)[model.losses firstObject]).multiple;
    
            self.currentApplyMoney = self.curretStrategyModel.currentApplyMoeny;
        }else
        {
            self.curretStrategyModel.currentApplyMoeny = self.currentApplyMoney;
        }
        
      
      
    }
}

//添加子控件
-(void)addChildViews
{
    [self topView];
    [self tableView];
    [self buttonView];
    [self.tableView reloadData];
    //默认开关打开
    self.autoPaySwitch = [UISwitch new];
    [self.autoPaySwitch setOn:YES];
}



#pragma mark UITableViewDelegate , UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.selectBlockList.count;
    }else{
        return 7;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return [YDSelectBuyBlockCell headviewHeightWithData:[self.selectBlockList objectAtIndex:indexPath.row]];
    }else
    {
        return isPhoneX ? rateX812(40) : rate750(40);
    }
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        YDSelectBuyBlockCell *cell =  [YDSelectBuyBlockCell cellWithTableView:tableView];
        
        cell.cellRow = indexPath.row;
        
        
        cell.currentApplyMoney = self.currentApplyMoney;
        cell.fundsArray = [self.selectBlockList objectAtIndex:indexPath.row];;//传递申请资金的数组
        
        cell.index = [[self.indexList objectAtIndex:indexPath.row] integerValue];
        
        [cell setClickFinishBlock:^(SelectBlockType type, NSString *fundMoney,NSInteger index) {
            
            if (type == ApplyMoney) {
                //申请资金
                self.curretStrategyModel.currentApplyMoeny = fundMoney;
                self.currentApplyMoney = fundMoney;
                [self.indexList replaceObjectAtIndex:type withObject:@(index)];
                [self refreshFooter0];
                [self reloadSection];
            }
            else if (type == CarryDay)
            {
                //持仓天数
                [self configurationDataSourceWithIndex:index isTwice:YES];
                
                
                //如果当前持仓天数的申请资金count不一样 默认选第一个申请资金
                if (self.curretStrategyModel.amountValues.count != self.fundsArray1.count) {

                    [self.indexList replaceObjectAtIndex:0 withObject:@0];
                    [self.indexList replaceObjectAtIndex:2 withObject:@(index)];
                    [self.tableView reloadData];
//
                }else
                {
                    [self.indexList replaceObjectAtIndex:type withObject:@(index)];
                    [self reloadSection];
                }
                
                
                if (self.curretStrategyModel.losses.count !=  self.gangganList.count) {

                    //止损率
                    self.currenLosetRate = ((YDLossRateModel *)[self.curretStrategyModel.losses objectAtIndex:0]).point;
                    //杠杆倍数
                     self.currentLossMultiple = ((YDLossRateModel *)[self.curretStrategyModel.losses objectAtIndex:0]).multiple;
                    
                    [self.indexList replaceObjectAtIndex:1 withObject:@0];
                    [self.indexList replaceObjectAtIndex:2 withObject:@(index)];
                    [self.tableView reloadData];
                }else
                {
                   
                    [self.indexList replaceObjectAtIndex:type withObject:@(index)];
                    [self reloadSection];
                }
                
                [self.fundsArray1 removeAllObjects];
                [self.gangganList removeAllObjects];

                for (YDAccountMonyModel *model1 in self.curretStrategyModel.amountValues) {//金额
                    [self.fundsArray1 addObject:model1.wanValue];
                }
                for (YDLossRateModel *model1 in self.curretStrategyModel.losses) { //杠杆
                    [self.gangganList addObject:[NSString stringWithFormat:@"%@",model1.multiple]];
                }
                
                
            }
            else if (type == LeverBalance)
            {
                //杠杆倍数选择只改变止损率 履约保证金
                
                [self.indexList replaceObjectAtIndex:type withObject:@(index)];
                self.currenLosetRate = ((YDLossRateModel *)[self.curretStrategyModel.losses objectAtIndex:index]).point;
               self.currentLossMultiple = ((YDLossRateModel *)[self.curretStrategyModel.losses objectAtIndex:index]).multiple;
                [self reloadSection];

            }
            
        }];
        
        return cell;
    }else
    {
        YDBuyStrategyCell *cell = [YDBuyStrategyCell cellWithTableView:tableView];
        cell.delegate = self;
        
        //隐藏箭头
        cell.accImage.hidden = YES;

        if (indexPath.row == 6) {
            //最后一行显示开关
            cell.autoSwitch.hidden = NO;
        }else
        {
            cell.autoSwitch.hidden = YES;
        }
        
        if (indexPath.row == 0) {
            cell.questionImage.hidden = YES;
            cell.cateLabel.text = @"触发止盈";
            cell.detailLabel.textColor = [UIColor colorWithHexString:paleRed];
            cell.detailLabel.text = [NSString stringWithFormat:@"%.1f%%",self.curretStrategyModel.profit.floatValue *100];
            
        }else if (indexPath.row == 1){
            cell.questionImage.hidden = YES;
            cell.cateLabel.text = @"触发止损";
            cell.detailLabel.textColor = [UIColor colorWithHexString:leafyGreen];
            NSString *point = self.currenLosetRate;
            cell.detailLabel.text = [NSString stringWithFormat:@"-%.1f%%",point.floatValue * 100];
        }else if (indexPath.row == 2){
            cell.questionImage.hidden = YES;
            cell.detailLabel.textColor = [UIColor colorWithHexString:dark];
            cell.cateLabel.text = @"持仓时间";
            cell.detailLabel.text = [NSString stringWithFormat:@"T+%@", self.curretStrategyModel.cycle];
        }else if (indexPath.row == 3){
            cell.questionImage.hidden = NO;
            cell.cateLabel.text = @"信息服务费";
            cell.detailLabel.textColor = [UIColor colorWithHexString:dark];
            cell.detailLabel.text = [NSString stringWithFormat:@"%@元",[self getCurrentServiceFeeWithCurrentApplyMoeny:self.curretStrategyModel.currentApplyMoeny]];
        }else if (indexPath.row == 4){
            cell.questionImage.hidden = NO;
            cell.cateLabel.text = @"履约保证金";
            cell.detailLabel.textColor = [UIColor colorWithHexString:dark];
            cell.detailLabel.text = [NSString stringWithFormat:@"%@元" , [self countSecurityMoneyWithValue:self.curretStrategyModel.currentApplyMoeny]];
        }else if (indexPath.row == 5){
            cell.questionImage.hidden = NO;
            cell.cateLabel.text = @"递延费";
            cell.detailLabel.textColor = [UIColor colorWithHexString:dark];
            cell.detailLabel.text = [NSString stringWithFormat:@"%@元/天",[self getCurrentdeferredFeeWithCurrentdeferredMoeny:self.curretStrategyModel.currentApplyMoeny]];
        }else if (indexPath.row == 6)
        {
            [cell.autoSwitch setOn:YES];
            [self.autoPaySwitch setOn:YES];
            cell.questionImage.hidden = YES;
            cell.cateLabel.text = @"到期自动支付递延费";
            cell.detailLabel.text = nil;
            
        }
        
        return cell;
    }
    
    
}

/**
 刷新section1
 */
- (void)reloadSection
{
    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return isPhoneX ? rate375(27) : rate750(27);
    }else
    {
        return isPhoneX ? rate375(50) : rate750(50);
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        self.footer0 = [YDSelectBuyBlockFooter footerViewWithTableView:tableView];
        [self refreshFooter0];
        return self.footer0;
    }
    else
    {
        self.footer = [YDBuyStrategyTableFooterView footerViewWithTableView:tableView];
        
        [self reFreshFooter];
        return self.footer;
    }
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [UIView new];
}
// 解决tableview group模式下的 section留白
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0001;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    if (indexPath.row == 1 && indexPath.section == 1){//选择止损
//        [self rateView];
//    }
}



/**
 刷新footer的数字
 */
-(void)reFreshFooter
{
    NSString *diyanFee = self.autoPaySwitch.isOn ? self.curretStrategyModel.currentdeferredFee :@"0";
    
    self.allMoneyStr = [[self.curretStrategyModel.currentsecurityMoeny pz_stringNumberByAdding:self.curretStrategyModel.currentServiceFee] pz_stringNumberByAdding:diyanFee];
    
    
    self.footer.amountaString = [NSString countNumAndChangeformat:self.allMoneyStr];
}

/**
 刷新section为0的footer
 */
- (void)refreshFooter0
{
    self.footer0.currentMoney = self.curretStrategyModel.currentApplyMoeny;
    self.footer0.stockMarket = self.currentStock;
}

#pragma mark - getter

//顶部显示单只股票的view
-(YDBuyStrategyTopView *)topView
{
    if (_topView == nil) {
        YDBuyStrategyTopView *topView = [YDBuyStrategyTopView buyStrategyTopViewWithStockDict:self.currentStock];
        [self.view addSubview:topView];
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(74)));
            }else{
                make.height.equalTo(@(rate750(74)));
            }
            
        }];
        _topView = topView;
    }
    return _topView;
}

///////tbaleView********////
-(UITableView *)tableView
{
    if (_tableView == nil) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            make.top.equalTo(self.topView.mas_bottom);
        }];
        if (isPhoneX) {
            tableView.contentInset = UIEdgeInsetsMake(-25, 0, rateX812(63), 0);
        }else{
            tableView.contentInset = UIEdgeInsetsMake(-25, 0, rate750(50), 0);
        }
   
        _tableView = tableView;
    }
    return _tableView;
}

//#pragma mark - 选择止损率view
//-(YDBuySelectedRateView *)rateView
//{
//    if (_rateView == nil) {
//        YDBuySelectedRateView *rateView = [YDBuySelectedRateView buySelectedRateViewWithModelArray:self.selectedRateArray];
//        rateView.currentLoseRate = self.currenLosetRate ? self.currenLosetRate : [self firstLoseRate];
//        rateView.frame = [UIScreen mainScreen].bounds;
//        [[UIApplication sharedApplication].keyWindow addSubview:rateView];
//        rateView.delegate = self;
//        _rateView = rateView;
//    }
//    return _rateView;
//}

#pragma YDRechargeWithdrawalButtonView
/////********立即买入按钮*******///////
-(YDRechargeWithdrawalButtonView *)buttonView
{
    if (_buttonView == nil) {
        YDRechargeWithdrawalButtonView *buttonView = [YDRechargeWithdrawalButtonView rechargeWithdrawalButtonWithButtonTitle:@"发布策略"];
        [self.view addSubview:buttonView];
        
        [buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
            if (isPhoneX) {
                make.height.equalTo(@(rateX812(63)));
            }else{
                make.height.equalTo(@(rate750(50)));
            }
        }];
        buttonView.delegate = self;
        [buttonView enableButton];
        _buttonView = buttonView;
    }
    return _buttonView;
}

#pragma SYBuyStrategyCellDelegate
-(void)buyStrategyCellQuestionImageClick:(YDBuyStrategyCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row == 3) {//信息服务费
        [self showQuestionTipsViewWithTipsString:@"信息服务费指点买人需要支付给平台的费用，此费用根据交易金额收取，方案金额越大，服务费越高" PostTitle:@"信息服务费" ButtonTitle:@"知道了"];
    }else if (indexPath.row == 4){//履约保证金
        [self showQuestionTipsViewWithTipsString:@"履约保证金是平台冻结在三方支付公司，用于方案亏损时的赔付义务的费用，结束时根据方案盈亏结算，如盈利，全额返还。如亏损，按实际亏损赔付" PostTitle:@"履约保证金" ButtonTitle:@"知道了"];
    }else if (indexPath.row == 5){//递延费
        [self showQuestionTipsViewWithTipsString:@"勾选递延费后,需要扣除当天的递延费（只递延一天），在不出现止盈，止损的情况下可以持该方案一天到下一个交易日，如当天到达止盈、止损线，递延费将退回您的账户" PostTitle:@"递延费" ButtonTitle:@"知道了"];
    }
}



-(void)showQuestionTipsViewWithTipsString:(NSString *)string PostTitle:(NSString *)postTitle ButtonTitle:(NSString *)buttonTitle
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:postTitle Mesage:string ButtonTitle:buttonTitle ButtonClickBlock:^{
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

-(void)swicthDidSwitch:(UISwitch *)swich
{
    self.autoPaySwitch = swich;
    [self reFreshFooter];
}




#pragma mark PZBuySelectedRateViewDelegate
-(void)buySelectedRateViewDismissButtonClick
{
    [self.rateView removeFromSuperview];
    self.rateView = nil;
}

-(void)didSelectedRateString:(NSString *)rateStr
{
    DDLog(@"点击选中的比率:%@",rateStr);
    self.currenLosetRate = rateStr;

    [self reloadSection];
}


#pragma mark - private method
- (NSString *)countSecurityMoneyWithValue:(NSString *)value
{
    //计算履约金
    NSString *v = [NSString stringWithFormat:@"%lf",( value.length ? value.floatValue : 1) * 10000];
    
    SYDecimalNumberHandler *hander = [SYDecimalNumberHandler shareHanderWithRoundingMode:NSRoundDown scale:5 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    
    NSString *money =  [[self.curretStrategyModel.wearingPoint pz_stringNumberByAdding:self.currenLosetRate withBehavior:hander] pz_stringNumberByMultiplyingBy:v];
    
    self.curretStrategyModel.currentsecurityMoeny = money;
    NSString *formateMoney = [NSString countNumAndChangeformat:money];
    return formateMoney;
}

-(NSString *)getCurrentServiceFeeWithCurrentApplyMoeny:(NSString *)applyMoney
{
    //计算信息服务费
    //获取每万元服务费
    NSString *perWan = self.curretStrategyModel.serviceFeePerWan;
    
    NSString *money = [perWan pz_stringNumberByMultiplyingBy:applyMoney];
    
    self.curretStrategyModel.currentServiceFee = money;
    
    NSString *formateMoney = [NSString countNumAndChangeformat:money];
    
    return formateMoney;
}
-(NSString *)getCurrentdeferredFeeWithCurrentdeferredMoeny:(NSString *)applyMoney
{
    //计算递延费
    //获取每万元递延费
    NSString *perWan = self.curretStrategyModel.deferred;
    
    NSString *money = [perWan pz_stringNumberByMultiplyingBy:applyMoney];
    
    self.curretStrategyModel.currentdeferredFee = money;
    
    NSString *formateMoney = [NSString countNumAndChangeformat:money];
    
    return formateMoney;
}


#pragma mark - 获取设置支付密码信息
-(void)loadUserCardBindInfo
{
    
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetSettingInformationList WithSuccessBlock:^(NSDictionary *resultDict) {
       [[SYProgressHUD sharedInstance] dismissMBWithTime:0];

        if ([resultDict[@"code"] integerValue] == 200) {
            
            BOOL isBindCard = [resultDict[@"result"][@"settingPaymentPassword"] boolValue];
            
            if (!isBindCard) {
               
                [self goSetupPayPassword];
            }
            else
            {
                [self pay];
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failBlock:^(NSError *error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"信息加载出错，请重试~" isExistNav:YES];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
-(void)goSetupPayPassword
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"您还没有设置支付密码，请先设置支付密码" ButtonTitle:@"去设置" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
        YDPaymentPasswordController *vc = [[YDPaymentPasswordController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}
/////*********点击买入按钮************///////
#pragma PZRechargeWithdrawalButtonViewDelegate 点买
-(void)rechargeWithdrawalButtonViewButtonClick
{
    DDLog(@"立即买入")

    if (![SYUserInformation sharedInstance].isLogin) {
        //没有登录直接弹登录页面
        [self presentLoginVC];
        return;
    }

     //非交易时间段弹窗
    if(![NSDate stockTradingTimeJudgment])
    {
        [self noTransactionTimeAlert];
        return;
    }

    //获取是否设置银行卡信息
    [self loadUserCardBindInfo];

}

#pragma mark - 点买
- (void)pay
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setObject:@(self.curretStrategyModel.Id) forKey:@"strategyTypeId"];//策略类型ID
    [dict setObject:@(self.curretStrategyModel.currentApplyMoeny.floatValue * 10000) forKey:@"applyAmount"];//申请是市值
    
    [dict setObject:@(self.curretStrategyModel.currentServiceFee.floatValue) forKey:@"serviceFee"];//服务费
    [dict setObject:@(self.curretStrategyModel.currentsecurityMoeny.floatValue) forKey:@"reserveFund"];//保证金
    [dict setObject:self.curretStrategyModel.profit forKey:@"profitPoint"];//止盈点
    [dict setObject:@(-self.currenLosetRate.floatValue) forKey:@"lossPoint"];//止损点
    [dict setObject:self.currentStock[@"instrumentId"] forKey:@"stockCode"];//股票代码
    [dict setObject:@(self.autoPaySwitch.isOn) forKey:@"deferred"];//是否递延
    [dict setObject:self.currentStock[@"upLimitPrice"] forKey:@"delegatePrice"];//股票最新价
    [dict setObject:self.autoPaySwitch.isOn ?  self.curretStrategyModel.currentdeferredFee :@0 forKey:@"deferredFee"]; //当前递延费
    
    [dict setObject:self.currentLossMultiple forKey:@"lossMultiple"];//当前杠杆倍数
    DDLog(@"dict = %@" , dict)
    
    
    YDPayAlertView *payView = [[YDPayAlertView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, LKScreenH) inputFinish:^(NSString *passWord) {
        
        [dict setObject:passWord forKey:@"paymentPassword"];
        [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
        [BaseNetRequest sessionRequestWithparameters:dict
                                                   method:POSTMethod
                                               requstType:BuyStock
                                         WithSuccessBlock:^(NSDictionary *resultDict) {
                                             [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                                             if ([resultDict[@"code"] integerValue] == 200)
                                             {
                                                 
                                                 [[SYUserDataManger sharedInstance] currentAccountBalanceChangeWithUsedAmountString:self.allMoneyStr IsAdd:NO];
                                                 
                                                 
                                                 [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                 WithType:NavTipsViewTypeSuccess text:@"购买成功"
                                                                                               isExistNav:YES];
                                                 
                                                 if (self.autoPaySwitch.isOn) {
                                                     [self showAutoPayAlert];
                                                 }else
                                                 {
                                                     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

                                                         [self.navigationController popToRootViewControllerAnimated:NO];
                                                         
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             [[NSNotificationCenter defaultCenter] postNotificationName:kBuySuccessNoti object:nil];
                                                         });
                                                         
                                                     });
                                                 }
                                                 
                                                 
                                             }
                                             else if ([resultDict[@"code"] integerValue] == 6001)
                                             {
                                                 //账号余额不足
                                                 [self showAccountBalanceNotEnoughAlert];
                                                 
                                             }
                                             else if ([resultDict[@"code"] integerValue] == 6013)
                                             {
                                                 //非交易时间段
                                                 [self noTransactionTimeAlert];
                                             }
                                             else
                                             {
                                                 
                                                 [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                 WithType:NavTipsViewTypeMessage text:resultDict[@"message"]
                                                                                               isExistNav:YES];
                                             }
                                             
                                         } failBlock:^(NSError *error) {
                                             [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
                                             
                                             if ([ErrorMessageManager showErrorMessageWithError:error vc:self]) {
                                                 
                                             }
                                             else
                                             {
                                                 [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                                                                 WithType:NavTipsViewTypeMessage
                                                                                                     text:@"信息加载出错！"
                                                                                               isExistNav:YES];
                                             }
                                         }];
    }];
    [payView show];
    
}
- (void)showAccountBalanceNotEnoughAlert
{
    //账户余额不足提示
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"账户余额不足，请先充值！" ButtonTitle:@"去充值" ButtonClickBlock:^{
        
        [self.navigationController pushViewController:[[YDRechargeController alloc] init] animated:YES];
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}



- (void)noTransactionTimeAlert
{
    //非交易时间段弹窗
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"现在是非交易时间段，请在交易时间内点买。\n交易时间段：（国家法定节假日除外）周一至周五\n09:30-11:30 13:00-14:50" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

- (void)showAutoPayAlert
{
    
    //开启自动支付 点买成功提示
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"勾选递延费后,需要扣除当天的递延费（只递延一天），在不出现止盈，止损的情况下可以持有方案一天到下一个交易日，如当天到达止盈、止损线，递延费将退回您的账户!" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        
        [self.navigationController popToRootViewControllerAnimated:NO];
        [self.pz_popupController dismiss];
        dispatch_async(dispatch_get_main_queue(), ^{
             [[NSNotificationCenter defaultCenter] postNotificationName:kBuySuccessNoti object:nil];
        });
        
       
        
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

- (void)presentLoginVC
{
    YDLoginController *loginVC = [[YDLoginController alloc] init];
    loginVC.loginStyle = Login_Present;
    YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:baseNav animated:YES completion:nil];
}



@end
